package cn.t.web.applet;

import cn.t.constants.ParamConstants;
import cn.t.constants.ResponseError;
import cn.t.core.exception.BizException;
import cn.t.core.mode.PageInfoDTO;
import cn.t.core.mode.PageQueryDTO;
import cn.t.core.mode.Result;
import cn.t.dto.device.CabinetHandlingOCDTO;
import cn.t.dto.device.CargowayDTO;
import cn.t.dto.device.EmptyCargowayReq;
import cn.t.dto.device.group.CloseGroup;
import cn.t.dto.order.ReplenishmentDetailDTO;
import cn.t.dto.order.android.ReplenishmentTotalDTO;
import cn.t.dto.order.base.OrderSnRequest;
import cn.t.dto.order.base.VBaseDTO;
import cn.t.dto.order.repenlement.ReplenishmentPageDTO;
import cn.t.dto.order.repenlement.ReplenishmentQueryRequest;
import cn.t.enums.device.DeviceTypeEnum;
import cn.t.enums.order.ReplenishmentStatusEnum;
import cn.t.facade.android.ReplenishmentAndroidFacade;
import cn.t.facade.android.engine.CabinetHandlingStrategy;
import cn.t.facade.device.CargowayFacade;
import cn.t.facade.device.CargowaySkuFacade;
import cn.t.facade.device.DeviceFacade;
import cn.t.facade.order.ReplenishmentDetailFacade;
import cn.t.facade.order.ReplenishmentFacade;
import cn.t.vo.device.DeviceBaseInfoVO;
import cn.t.web.android.config.DeviceTypeHandlerFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 小程序-补货管理
 * @author l
 */
@Slf4j
@RestController
@RequestMapping("applet/replenishment")
@AllArgsConstructor
public class AppletReplenishmentController {
    private final DeviceTypeHandlerFactory deviceTypeHandlerFactory;
    @Resource
    private ReplenishmentAndroidFacade replenishmentAndroidFacade;
    @Resource
    private ReplenishmentFacade replenishmentFacade;
    @Resource
    private ReplenishmentDetailFacade replenishmentDetailFacade;
    @Resource
    private final CargowaySkuFacade cargowaySkuFacade;
    @Resource
    private final DeviceFacade deviceFacade;
    @Resource
    private final CargowayFacade cargowayFacade;
    /**
     * 补货单列表
     */
    @PostMapping(value = "/List")
    public PageInfoDTO<ReplenishmentPageDTO> replenishmentList(@RequestBody PageQueryDTO<ReplenishmentQueryRequest> pageQueryDTO) {
        return replenishmentAndroidFacade.queryAppletDataList(pageQueryDTO);
    }
    /**
     * 补货单详情
     */
    @PostMapping(value = "/detail")
    public VBaseDTO<ReplenishmentPageDTO, ReplenishmentDetailDTO> replenishmentDetail(@Validated @RequestBody OrderSnRequest request) {
        String rsSn = request.getOrderSn();
        if (ObjectUtils.isEmpty(rsSn)) {
            throw new BizException(ResponseError.PARAM_NOT_FOUND, "rsSn不能为空");
        }
        ReplenishmentPageDTO replenishmentInfo = replenishmentFacade.findReplenishmentInfo(rsSn);
        List<ReplenishmentDetailDTO> replenishmentDetailList = replenishmentDetailFacade.getReplenishmentDetailList(Collections.singletonList(rsSn));
        if (DeviceTypeEnum.ROTATING_CABINET.getCode().equals(replenishmentInfo.getDeviceType())){
            //查询货道信息
            Map<Integer, CargowayDTO> cargowayMap = cargowayFacade.getInfoByDeviceId(replenishmentInfo.getDeviceId()).stream().collect(Collectors.toMap(CargowayDTO::getCargowayNo, Function.identity()));
            // 使用自定义收集器进行分组
            Map<Integer, List<ReplenishmentDetailDTO>> groupedLists = replenishmentDetailList.stream().peek(detailDTO -> detailDTO.setLineNum(cargowayMap.get(detailDTO.getCargowayNo())==null?null:cargowayMap.get(detailDTO.getCargowayNo()).getLineNum()))
                    .sorted(Comparator.comparingInt(ReplenishmentDetailDTO::getLineNum)).collect(Collectors.groupingBy(ReplenishmentDetailDTO::getLineNum));
            return    new VBaseDTO<>(replenishmentInfo, groupedLists);
        }
     return    new VBaseDTO<>(replenishmentInfo, replenishmentDetailList);
    }

    /**
     * 补货单分类汇总
     */
    @GetMapping(value = "/replenishmentCount")
    public ReplenishmentTotalDTO countNum() {
        return replenishmentAndroidFacade.queryAppletReplenishmentSum();
    }


    /**
     * 补货关门
     */
    @PostMapping("/replenishmentClose")
    public Result<Boolean> close(@Validated(CloseGroup.class) @RequestBody CabinetHandlingOCDTO model) {
        long startTime = System.currentTimeMillis();
        DeviceBaseInfoVO device = deviceFacade.deviceBaseInfo(model.getDeviceId());
        CabinetHandlingStrategy handler1 = deviceTypeHandlerFactory.getHandler(ParamConstants.CABINET_TYPE + device.getDeviceType());
        Result<Boolean> result = Result.success(true);
        try {
            model.setDeviceId(device.getDeviceId());
            Boolean aBoolean = handler1.replenishmentGoodsClose(model);

            if (!aBoolean) {
                log.warn("补货关门失败 {}", model.getOrderSn());
                result = Result.fail(ResponseError.DATA_ERR.getCode(), "补货关门失败");
            }
        } catch (Exception e) {
            log.warn("补货关门异常", e);
            if (e.getMessage() != null) {
                throw new BizException(ResponseError.DATA_ERR, e.getMessage());
            } else {
                throw new BizException(ResponseError.DATA_ERR, "关门异常,请联系管理员!");
            }
        }
        log.info("补货关门-结束耗时 {}", System.currentTimeMillis() - startTime);
        return result;
    }
    /**
     * 空货道列表
     */
    @PostMapping("/emptyCargoway")
    public Map<Integer, List<ReplenishmentDetailDTO>> emptyCargoway(@Validated @RequestBody EmptyCargowayReq req) {
        ReplenishmentPageDTO replenishmentInfo = replenishmentFacade.findReplenishmentInfo(req.getRsSn());
        List<ReplenishmentDetailDTO> replenishmentDetailList = replenishmentDetailFacade.getReplenishmentDetailList(Collections.singletonList(req.getRsSn()));
            //查询货道信息
            Map<Integer, CargowayDTO> cargowayMap = cargowayFacade.getInfoByDeviceId(replenishmentInfo.getDeviceId()).stream().collect(Collectors.toMap(CargowayDTO::getCargowayNo, Function.identity()));
            // 使用自定义收集器进行分组
          return replenishmentDetailList.stream().filter(info-> ReplenishmentStatusEnum.PENDING.getCode().equals(info.getRsGoodsStatus())).peek(detailDTO -> detailDTO.setLineNum(cargowayMap.get(detailDTO.getCargowayNo())==null?null:cargowayMap.get(detailDTO.getCargowayNo()).getLineNum()))
                    .sorted(Comparator.comparingInt(ReplenishmentDetailDTO::getLineNum)).collect(Collectors.groupingBy(ReplenishmentDetailDTO::getLineNum));

}
}
